<template>
    <div class="collection-container">
        <el-card class="action-card">
            <template #header>
                <div class="card-header">
                    <h3>数据采集任务</h3>
                    <el-button type="primary" @click="handleCreateTask">
                        创建任务
                    </el-button>
                </div>
            </template>
            
            <el-table :data="tasks" v-loading="loading" style="width: 100%">
                <el-table-column prop="name" label="任务名称" />
                <el-table-column prop="data_source.name" label="数据源" />
                <el-table-column prop="status" label="状态">
                    <template #default="scope">
                        <el-tag :type="getStatusTag(scope.row.status)">
                            {{ getStatusText(scope.row.status) }}
                        </el-tag>
                    </template>
                </el-table-column>
                <el-table-column prop="progress" label="进度" width="200">
                    <template #default="scope">
                        <el-progress 
                            :percentage="scope.row.progress"
                            :status="getProgressStatus(scope.row.progress, scope.row.status)"
                        />
                    </template>
                </el-table-column>
                <el-table-column prop="created_at" label="创建时间">
                    <template #default="scope">
                        {{ formatDate(scope.row.created_at) }}
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="200">
                    <template #default="scope">
                        <el-button-group>
                            <el-button 
                                v-if="scope.row.status === 'pending'"
                                type="primary" 
                                :icon="CaretRight"
                                @click="handleStart(scope.row)"
                            >
                                开始
                            </el-button>
                            <el-button 
                                v-if="scope.row.status === 'running'"
                                type="warning" 
                                :icon="VideoPause"
                                @click="handlePause(scope.row)"
                            >
                                暂停
                            </el-button>
                            <el-button 
                                v-if="['pending', 'running'].includes(scope.row.status)"
                                type="danger" 
                                :icon="CircleClose"
                                @click="handleCancel(scope.row)"
                            >
                                取消
                            </el-button>
                            <el-button 
                                type="danger" 
                                :icon="Delete"
                                @click="handleDelete(scope.row)"
                            >
                                删除
                            </el-button>
                        </el-button-group>
                    </template>
                </el-table-column>
            </el-table>
        </el-card>

        <!-- 创建任务对话框 -->
        <el-dialog 
            v-model="dialogVisible" 
            title="创建采集任务"
            width="600px"
        >
            <el-form 
                ref="formRef"
                :model="form"
                :rules="rules"
                label-width="100px"
            >
                <el-form-item label="任务名称" prop="name">
                    <el-input v-model="form.name" placeholder="请输入任务名称" />
                </el-form-item>
                
                <el-form-item label="数据源" prop="data_source">
                    <el-select 
                        v-model="form.data_source" 
                        placeholder="请选择数据源"
                        style="width: 100%"
                    >
                        <el-option
                            v-for="source in dataSources"
                            :key="source.id"
                            :label="source.name"
                            :value="source.id"
                        />
                    </el-select>
                </el-form-item>
                
                <el-form-item label="关键词" prop="parameters.keywords">
                    <el-select
                        v-model="form.parameters.keywords"
                        multiple
                        filterable
                        allow-create
                        default-first-option
                        placeholder="请输入关键词（可多选）"
                        style="width: 100%"
                    />
                </el-form-item>
                
                <el-form-item label="时间范围">
                    <el-date-picker
                        v-model="form.parameters.date_range"
                        type="daterange"
                        range-separator="至"
                        start-placeholder="开始日期"
                        end-placeholder="结束日期"
                        style="width: 100%"
                    />
                </el-form-item>
                
                <el-form-item label="最大条数" prop="parameters.max_items">
                    <el-input-number 
                        v-model="form.parameters.max_items"
                        :min="1"
                        :max="10000"
                    />
                </el-form-item>
            </el-form>
            
            <template #footer>
                <el-button @click="dialogVisible = false">取消</el-button>
                <el-button type="primary" @click="handleSubmit" :loading="submitting">
                    确定
                </el-button>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
    CaretRight,
    VideoPause,
    CircleClose,
    Delete
} from '@element-plus/icons-vue'
import { analysisApi } from '@/api/analysis'

const loading = ref(false)
const dialogVisible = ref(false)
const submitting = ref(false)
const tasks = ref([])
const dataSources = ref([])
const formRef = ref(null)

// 表单数据
const form = ref({
    name: '',
    data_source: '',
    parameters: {
        keywords: [],
        date_range: [],
        max_items: 1000
    }
})

// 表单验证规则
const rules = {
    name: [
        { required: true, message: '请输入任务名称', trigger: 'blur' },
        { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
    ],
    data_source: [
        { required: true, message: '请选择数据源', trigger: 'change' }
    ],
    'parameters.keywords': [
        { required: true, message: '请至少输入一个关键词', trigger: 'change' },
        { type: 'array', min: 1, message: '请至少输入一个关键词', trigger: 'change' }
    ],
    'parameters.max_items': [
        { required: true, message: '请输入最大采集条数', trigger: 'blur' },
        { type: 'number', min: 1, max: 10000, message: '采集条数范围在1-10000之间', trigger: 'blur' }
    ]
}

// 获取任务列表
const fetchTasks = async () => {
    loading.value = true
    try {
        const response = await analysisApi.getTasks()
        tasks.value = response.results || []
    } catch (error) {
        ElMessage.error('获取任务列表失败')
        console.error('Error fetching tasks:', error)
    } finally {
        loading.value = false
    }
}

// 获取数据源列表
const fetchDataSources = async () => {
    try {
        const response = await analysisApi.getDataSources()
        dataSources.value = response.results || []
    } catch (error) {
        ElMessage.error('获取数据源列表失败')
        console.error('Error fetching data sources:', error)
    }
}

// 创建任务
const handleCreateTask = () => {
    form.value = {
        name: '',
        data_source: '',
        parameters: {
            keywords: [],
            date_range: [],
            max_items: 1000
        }
    }
    dialogVisible.value = true
}

// 开始任务
const handleStart = async (task) => {
    try {
        await analysisApi.startTask(task.id)
        ElMessage.success('任务已启动')
        fetchTasks()
    } catch (error) {
        ElMessage.error('启动任务失败')
    }
}

// 暂停任务
const handlePause = async (task) => {
    try {
        await analysisApi.cancelTask(task.id)
        ElMessage.success('任务已暂停')
        fetchTasks()
    } catch (error) {
        ElMessage.error('暂停任务失败')
    }
}

// 取消任务
const handleCancel = async (task) => {
    try {
        await ElMessageBox.confirm(
            '确定要取消该任务吗？',
            '警告',
            {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }
        )
        
        await analysisApi.cancelTask(task.id)
        ElMessage.success('任务已取消')
        fetchTasks()
    } catch (error) {
        if (error !== 'cancel') {
            ElMessage.error('取消任务失败')
        }
    }
}

// 删除任务
const handleDelete = async (task) => {
    try {
        await ElMessageBox.confirm(
            '确定要删除该任务吗？删除后无法恢复。',
            '警告',
            {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }
        )
        
        await analysisApi.deleteTask(task.id)
        ElMessage.success('删除成功')
        fetchTasks()
    } catch (error) {
        if (error !== 'cancel') {
            ElMessage.error('删除失败')
        }
    }
}

// 提交表单
const handleSubmit = async () => {
    if (!formRef.value) return
    
    try {
        await formRef.value.validate()
        submitting.value = true
        
        // 处理日期范围
        if (form.value.parameters.date_range?.length === 2) {
            form.value.parameters.start_date = form.value.parameters.date_range[0]
            form.value.parameters.end_date = form.value.parameters.date_range[1]
        }
        delete form.value.parameters.date_range
        
        await analysisApi.createTask(form.value)
        ElMessage.success('创建成功')
        dialogVisible.value = false
        fetchTasks()
    } catch (error) {
        console.error('Error submitting form:', error)
        ElMessage.error('创建失败')
    } finally {
        submitting.value = false
    }
}

// 获取状态标签样式
const getStatusTag = (status) => {
    const statusMap = {
        pending: 'info',
        running: 'primary',
        completed: 'success',
        failed: 'danger',
        cancelled: 'warning'
    }
    return statusMap[status] || 'info'
}

// 获取状态文本
const getStatusText = (status) => {
    const statusMap = {
        pending: '等待中',
        running: '运行中',
        completed: '已完成',
        failed: '失败',
        cancelled: '已取消'
    }
    return statusMap[status] || status
}

// 获取进度条状态
const getProgressStatus = (progress, status) => {
    if (status === 'failed') return 'exception'
    if (status === 'completed') return 'success'
    if (progress === 100) return 'success'
    return ''
}

// 格式化日期
const formatDate = (date) => {
    return new Date(date).toLocaleString()
}

// 初始化
onMounted(() => {
    fetchTasks()
    fetchDataSources()
})
</script>

<style scoped>
.collection-container {
    padding: 20px;
}

.action-card {
    margin-bottom: 20px;
}

.card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.card-header h3 {
    margin: 0;
}

:deep(.el-dialog__body) {
    padding-top: 20px;
}

.el-button-group {
    display: flex;
    gap: 8px;
}

@media screen and (max-width: 768px) {
    .collection-container {
        padding: 12px;
    }
    
    .el-button-group {
        flex-direction: column;
    }
}
</style> 